package net.crowdloud.client.problem;

import java.util.List;

import net.crowdloud.shared.entities.Problem;
import net.crowdloud.shared.entities.User;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * 
 * @Feature
 */
public class ProblemList extends FlexTable {

	public ProblemList(User user, List<Problem> problems) {

		setBorderWidth(1);
		setWidth("900px");

		setCellPadding(5);

		gridColumns();

		gridRows(user, problems);
	}

	private void gridColumns() {

		this.setHTML(0, 0, "<B>TAGS</B>");
		this.getColumnFormatter().setWidth(0, "200px");

		this.setHTML(0, 1, "<B>Description</B>");
		this.getColumnFormatter().setWidth(1, "450px");

		this.setHTML(0, 2, "<B>Created</B>");
		this.getColumnFormatter().setWidth(2, "150px");

		this.setHTML(0, 3, "<B>Priority</B>");
		this.getColumnFormatter().setWidth(3, "50px");

		this.setHTML(0, 4, "<B>Estimative</B>");
		this.getColumnFormatter().setWidth(4, "50px");

		this.setHTML(0, 5, "<B>Status</B>");
		this.getColumnFormatter().setWidth(5, "50px");

		this.setHTML(0, 6, " ");
		this.getColumnFormatter().setWidth(6, "50px");
	}

	private void gridRows(User user, List<Problem> problems) {

		int row = 0;
		for (Problem problem : problems) {

			row++;

			this.setText(row, 0, problem.getTags());
			this.setText(row, 1, problem.getDescription());
			this.setText(row, 2, "");

			/*
			 * String priority = ""; if (backlogEntry.getBacklogPriority() !=
			 * null) { priority = backlogEntry.getBacklogPriority().toString();
			 * }
			 */
			this.setText(row, 3, "");

			this.setText(row, 4, "");

			this.setText(row, 5, "");

			HorizontalPanel hp = new HorizontalPanel();
			hp.setSpacing(10);
			hp.add(iconEdit(user, problem));
			hp.add(iconDelete(user, problem));

			this.setWidget(row, 6, hp);

		}
	}

	private static HTML iconEdit(final User user, final Problem problem) {

		HTML img = new HTML("<a href='#'><img src='images/edit.gif'></a>");
		img.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				RootPanel.get().clear();
				RootPanel.get().add(new ProblemForm(user, problem));
			}
		});

		img.setTitle("Edit Problem");

		return img;
	}

	private static HTML iconDelete(final User user, final Problem problem) {

		HTML img = new HTML("<a href='#'><img src='images/delete.gif'></a>");
		img.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				// new EditFeatureDescription(classe);
			}
		});

		img.setTitle("Delete Problem");

		return img;
	}
}
